package cn.xiaoyu.su.config;

import cn.xiaoyu.su.enums.BizCodeEnum;
import cn.xiaoyu.su.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author sufs
 * @date 2022/11/1 15:35
 */
@Configuration
@Slf4j
public class SnowFlakeWordIdConfig {

    /**
     * 动态指定sharding jdbc 的雪花算法中的属性work.id属性
     *
     * 通过调用System.setProperty()的方式实现，可用容器的id或者机器标识位
     * workId最大值 1L << 100,就是1024，即 0<= workId < 1024
     *
     * {@link SnowflakeShardingKeyGenerator#getWorkerId()}
     */
    static {
        try {
            InetAddress ip4 = Inet4Address.getLocalHost();
            String addressIp = ip4.getHostAddress();
            System.setProperty("workerId",(Math.abs(addressIp.hashCode())%1024)+"");
            log.info("workerId:{}",(Math.abs(addressIp.hashCode())%1024)+"");
        } catch (UnknownHostException e) {
            throw new BizException(BizCodeEnum.OPS_NETWORK_ADDRESS_ERROR);
        }
    }

}
